package com.chenfan.finance.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class SysThreadPoolConfig {

    @Value("${data.poll.thread.pool.config.corePoolSize:3}")
    private Integer corePoolSize;
    @Value("${data.poll.thread.pool.config.maxPoolSize:10}")
    private Integer maxPoolSize;
    @Value("${data.poll.thread.pool.config.keepAliveSeconds:120}")
    private Integer keepAliveSeconds;
    public static class DataPollThreadPool extends ThreadPoolTaskExecutor{

    }
    @Bean(name = "dataPollThreadPool")
    public DataPollThreadPool  asyncServiceExecutor() {
        DataPollThreadPool executor = new DataPollThreadPool();
        // 设置核心线程数
        executor.setCorePoolSize(corePoolSize);
        // 设置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        // 设置队列容量
        executor.setQueueCapacity(Integer.MAX_VALUE);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setThreadNamePrefix("TocDataPull-");
        executor.setAllowCoreThreadTimeOut(true);
        // 处理异常
        executor.setThreadFactory((Runnable r) -> {
            Thread thread = new Thread(r);
            thread.setName("TocDataPull-"+thread.getId());
            thread.setUncaughtExceptionHandler((Thread t, Throwable e) -> {
                throw new RuntimeException(e);
            });
            return thread;
        });

        executor.initialize();

        return executor;
    }


}
